﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace privacyUtils
{
    public class ECodeEngine
    {
        public ECodeEngine()
        {
            key = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        }

        #region Declaraciones

        private string key;

        #endregion Declaraciones

        #region Métodos

        public string encriptar(string texto)
        {
            byte[] keyArray;
            byte[] arrayACifrar = UTF8Encoding.UTF8.GetBytes(texto);

            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));

            hashmd5.Clear();

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateEncryptor();

            byte[] arrayResultado = cTransform.TransformFinalBlock(arrayACifrar, 0, arrayACifrar.Length);

            tdes.Clear();

            return Convert.ToBase64String(arrayResultado, 0, arrayResultado.Length);        
        }

        public string desencriptar(string textoEncriptado)
        {
            byte[] keyArray;
            byte[] arrayDescifrar = Convert.FromBase64String(textoEncriptado);

            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();

            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            hashmd5.Clear();

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateDecryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(arrayDescifrar, 0, arrayDescifrar.Length);

            tdes.Clear();

            return UTF8Encoding.UTF8.GetString(resultArray);
        }

        #endregion Métodos

    }
}
